package com.mishow.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.activity.base.TagActivity;
import com.mishow.fragment.DatePickerFragment;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.UserInfoResponse;
import com.mishow.request.result.User;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.DeviceUtil;
import com.mishow.utils.FileUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.mine.MultipartRequestParams;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.volley.http.request.MultipartRequest;
import com.mishow.volley.utils.BitmapUtil;
import com.mishow.widget.CircularImageView;
import com.mishow.widget.UploadImageDialog;

/**
 * 作者：wei.miao <br/>
 * 描述：个人资料
 */
@SuppressLint("SimpleDateFormat")
public class PersonDataActivity extends BaseActivity implements
		DatePickerFragment.DialogCallBackListener {

	private Button btn_back;
	private TextView title_right;

	private RelativeLayout relative_head;
	private RelativeLayout relative_nikename;
	private RelativeLayout relative_sex;
	private RelativeLayout relative_city;

	private RelativeLayout relative_id_number;
	private RelativeLayout relative_profession_type;
	private RelativeLayout relative_birthday;

	private TextView text_birthday;

	private EditText edit_nikename;
	private EditText edit_person_description;

	private CircularImageView img_head_icon;

	private TextView text_sex;
	private TextView text_city;

	private TextView text_id_number;
	private TextView text_relative_profession_type;

	/** 性别 **/
	private String mUserSex;
	/** 昵称 **/
	private String mUserNikeName;
	/** 出生日期 **/
	private String mInitBirthdayDate;
	/** 城市code **/
	private String cityCode; 
	/** 城市名称 **/
    private String cityName;

	private SharedPreferencesUtil mShPreferencesUtil;
	/**
	 * 上传图片对话框
	 **/
	private UploadImageDialog uploadImageDialog;
	
	/**
	 * 拍照的图片文件
	 **/
	private File cameraFile;

	private String fileImagePath;
	
	private int screenWidth;
    private int screenHeight;

	/** 职业类型显示标签 **/
	ArrayList<String> mProfessionTypeTags = new ArrayList<String>();

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public static void intoActivity(Context context) {

		Intent intent = new Intent(context, PersonDataActivity.class);
		context.startActivity(intent);

	}

	@Override
	protected void initData() {

		mInitBirthdayDate = "1990-01-02";
		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
		screenWidth = (int) DeviceUtil.getDeviceWidth(this);
        screenHeight = (int) DeviceUtil.getDeviceWidth(this);

	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		// 不显示程序的标题栏
		/*requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 不显示系统的标题栏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

		setContentView(R.layout.activity_person_data);
		btn_back = (Button) findViewById(R.id.btn_back);
		title_right = (TextView) findViewById(R.id.title_right);

		img_head_icon = (CircularImageView) findViewById(R.id.img_head_icon);

		relative_head = (RelativeLayout) findViewById(R.id.relative_head);
		relative_nikename = (RelativeLayout) findViewById(R.id.relative_nikename);
		relative_sex = (RelativeLayout) findViewById(R.id.relative_sex);
		relative_city = (RelativeLayout) findViewById(R.id.relative_city);

		relative_id_number = (RelativeLayout) findViewById(R.id.relative_id_number);
		relative_profession_type = (RelativeLayout) findViewById(R.id.relative_profession_type);
		relative_birthday = (RelativeLayout) findViewById(R.id.relative_birthday);

		edit_nikename = (EditText) findViewById(R.id.edit_nikename);

		text_birthday = (TextView) findViewById(R.id.text_birthday);

		edit_person_description = (EditText) findViewById(R.id.edit_person_description);

		text_sex = (TextView) findViewById(R.id.text_sex);

		text_city = (TextView) findViewById(R.id.text_city);
		text_id_number = (TextView) findViewById(R.id.text_id_number);
		text_relative_profession_type = (TextView) findViewById(R.id.text_relative_profession_type);
	}

	@Override
	protected void setAttribute() {
		setTitle("个人资料");
		title_right.setVisibility(View.VISIBLE);
		title_right.setText("保存");
		title_right.setTextColor(getResources().getColor(R.color.pale_red));

		btn_back.setOnClickListener(onClickListener);
		title_right.setOnClickListener(onClickListener);

		relative_head.setOnClickListener(onClickListener);
		relative_nikename.setOnClickListener(onClickListener);
		relative_sex.setOnClickListener(onClickListener);
		relative_city.setOnClickListener(onClickListener);
		relative_id_number.setOnClickListener(onClickListener);
		relative_profession_type.setOnClickListener(onClickListener);
		relative_birthday.setOnClickListener(onClickListener);

		selectSexDialog();
		// 获取用户基本信息
		doGetUserInfo();
	}

	private AlertDialog.Builder alertDialog;

	/**
	 * 选择性别对话框初始化
	 */
	private void selectSexDialog() {

		alertDialog = new AlertDialog.Builder(mContext);
		alertDialog.setItems(new String[] { "男", "女", "不限" },
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							text_sex.setText("男");
							text_sex.setTag("1");
							break;
						case 1:
							text_sex.setText("女");
							text_sex.setTag("2");
							break;
						case 2:
							text_sex.setText("不限");
							text_sex.setTag("0");
							break;
						}
					}
				});
		alertDialog.create();
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.title_right:// 保存
				if (parameterCheck()) {
					doUpdateUserInfo();
				}
				break;
			case R.id.relative_head:
				showUploadImageDialog();
				break;
			case R.id.relative_sex:
				alertDialog.show();
				break;
			case R.id.relative_city:
				// 弹出已开通城市列表
                CityListActivity.intoActivity(mContext);
				break;
			case R.id.relative_profession_type:
				TagActivity.intoActivityForResult(mContext, "profession_type",
						mProfessionTypeTags, "职业类型",
						Constants.REQUEST_TAG_PROFESSION_TYPE);
				break;
			case R.id.relative_birthday:
				DatePickerFragment.newInstance(PersonDataActivity.this,
						mInitBirthdayDate,true).show(
						mContext.getSupportFragmentManager(), "datePicker");
				break;
			default:
				break;
			}
		}
	};

	private boolean parameterCheck() {

		return true;
	}

	/**
	 * 更新用户个人资料
	 */
	private void doUpdateUserInfo() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);

		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());
		params.put("userCname", edit_nikename.getText().toString().trim()); // 用户昵称
		params.put("userJgTag", ""); // 极光推送tag
		params.put("userJgRegisterid", ""); // 极光推送注册ID
		params.put("userPhone", ""); // 手机号
		params.put("userProvince", ""); // 省名称
		params.put("userProvinceCode", ""); // 省编码
		params.put("userCity", text_city.getText().toString()); // 市名称
		params.put("userCityCode", ""); // 市编码
		params.put("userDistrict", ""); // 区名称
		params.put("userDistrictCode", ""); // 区编码
		if (!TextUtils.isEmpty(text_birthday.getText().toString())) {

			params.put("userBirth", text_birthday.getText().toString()); // 出生年月(Date日期类型)
		}else{
			
			params.put("userBirth", ""); // 出生年月(Date日期类型)
		}
		params.put("userAutograph", edit_person_description.getText().toString().trim()); // 个性签名
		
		params.put("userSex", text_sex.getTag().toString().trim()); // 用户性别(0-保密，1-男2-女)
		// 职业类型显示标签 
		if (mProfessionTypeTags != null && mProfessionTypeTags.size() > 0) {
			StringBuilder sBuilderTreatment = new StringBuilder();
			for (String tag : mProfessionTypeTags) {
				sBuilderTreatment.append(tag + ",");
			}
			String treatment = sBuilderTreatment.substring(0,
					sBuilderTreatment.length() - 1);
			params.put("userProfession", treatment); // 职业类型（多个类型用”,”
		} else {
			params.put("userProfession", ""); // 职业类型（多个类型用”,”
		}

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.UPDATE_USER_INFO);
		OnResponseListener<UserInfoResponse> listener = new OnResponseListener<UserInfoResponse>(
				this) {

			@Override
			public void onSuccess(UserInfoResponse response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				fillData(response.getBody().getResult());
			}

			@Override
			public void onError(String code, String message) {

			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<UserInfoResponse>(
				Request.Method.POST, postUrl, UserInfoResponse.class, listener,
				listener).setParams(lastParams));

	}

	/**
	 * 获取用户基础信息
	 */
	private void doGetUserInfo() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.USER_INFO);
		OnResponseListener<UserInfoResponse> listener = new OnResponseListener<UserInfoResponse>(
				this) {

			@Override
			public void onSuccess(UserInfoResponse response) {

				fillData(response.getBody().getResult());
			}

			@Override
			public void onError(String code, String message) {

			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<UserInfoResponse>(
				Request.Method.POST, postUrl, UserInfoResponse.class, listener,
				listener).setParams(lastParams));

	}

	/**
	 * 
	 * @param user
	 */
	private void fillData(User user) {

		edit_nikename.setText(user.getUserCname());
		if (!TextUtils.isEmpty(user.getUserCity())) {

			text_city.setText(user.getUserCity());
		}

		text_id_number.setText(user.getUserId() + "");
		if (!TextUtils.isEmpty(user.getUserProfession())) {

			text_relative_profession_type.setText(user.getUserProfession());

			mProfessionTypeTags.add(user.getUserProfession());
		}
		if (user.getUserBirth() != null) {

			String brithday = dateFormat.format(user.getUserBirth());
			text_birthday.setText(brithday);

		}
		if (!TextUtils.isEmpty(user.getUserAutograph())) {

			edit_person_description.setText(user.getUserAutograph());
		}

		int sex = user.getUserSex();
		if (sex == 1) {
			// 男
			text_sex.setText("男");
			text_sex.setTag("1");
		} else if (sex == 2) {
			// 女
			text_sex.setText("女");
			text_sex.setTag("2");
		} else {
			// 不限
			text_sex.setText("不限");
			text_sex.setTag("0");
		}

	}

	@Override
	public void callBack(String msg) {

		String birthday = msg;
		text_birthday.setText(birthday);
	}

	/**
	 * 上传图片
	 */
	private void showUploadImageDialog() {

		if (uploadImageDialog == null) {
			uploadImageDialog = new UploadImageDialog(this, R.style.ShareDialog);

			uploadImageDialog
					.setOnTakePhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							String filename = String.format("_%1$s.jpg",
									System.currentTimeMillis());
							cameraFile = new File(FileUtil
									.getStructureDirs(FileUtil.IMAGE_PATH),
									filename);
							Intent takeIntent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(cameraFile));
							startActivityForResult(takeIntent,
									Constants.REQUEST_CODE_TAKE_PHOTO);
						}
					});
			uploadImageDialog
					.setOnPickPhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent pickIntent = new Intent(Intent.ACTION_PICK,
									null);
							pickIntent
									.setDataAndType(
											MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											"image/*");
							startActivityForResult(pickIntent,
									Constants.REQUEST_CODE_PICK_PHOTO);
						}
					});
		}
		uploadImageDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case Constants.REQUEST_CODE_TAKE_PHOTO:
				handleFromCamera(data);
				break;
			case Constants.REQUEST_CODE_PICK_PHOTO:
				handleFromPhotos(data);
				break;
			case Constants.REQUEST_TAG_PROFESSION_TYPE:
				mProfessionTypeTags = data
						.getStringArrayListExtra(Constants.SELECTED_TAGS);
				displayTags(mProfessionTypeTags);
				break;
			case Constants.CITYLIST_CODE: // 城市列表返回
                if (data != null) {
                	text_city.setText(data.getExtras().getString(Constants.CITY_NAME)); // 城市名
                    cityCode = data.getExtras().getString(Constants.CITY_CODE);
                }
                break;
			default:
				break;
			}
		}
	}

	/**
	 * 页面显示标签
	 * 
	 * @param tags
	 */
	private void displayTags(ArrayList<String> tags) {
		if (tags.size() > 4) {

			ToastUtil.show(mContext, "职业类型不能超过4个");
			return;
		}
		text_relative_profession_type.setText("");
		StringBuilder sBuilder = new StringBuilder();
		for (String tag : tags) {
			sBuilder.append(tag + "\t");
		}
		text_relative_profession_type.setText(sBuilder.toString());
	}

	/**
	 * 相机拍照获取数据
	 */
	private void handleFromCamera(Intent data) {
		// 上传头象
		fileImagePath = cameraFile.getAbsolutePath();
		
		//上传图片到服务端
        String uploadFile = BitmapUtil.compressImage(fileImagePath, screenWidth, screenHeight);
		//上传图片到服务端
		doUploadImageTask(fileImagePath, uploadFile, img_head_icon);
	
	}

	/**
	 * 从手机相册获取数据
	 */
	private void handleFromPhotos(Intent data) {
		if (data == null) {
			return;
		}
		Uri selectedImage = data.getData();
		if (selectedImage == null) {
			return;
		}
		Cursor cursor = getContentResolver().query(selectedImage, null, null,
				null, null);
		String picturePath;
		if (cursor != null) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex("_data");
			picturePath = cursor.getString(columnIndex);
			cursor.close();
			cursor = null;

			if (picturePath == null || "".equals(picturePath)) {
				return;
			}
		} else {
			File file = new File(selectedImage.getPath());
			if (!file.exists()) {
				return;
			}
			picturePath = file.getAbsolutePath();
		}
		
		fileImagePath = picturePath;
        String uploadFile = BitmapUtil.compressImage(fileImagePath, screenWidth, screenHeight);
		//上传图片到服务端
		doUploadImageTask(fileImagePath, uploadFile, img_head_icon);
		
	}
	
	/**
     * 单次上传图片接口
     *
     * @param orignalFilePath
     * @param uploadFile 要上传的图片文件
     * @param displayImageView
     */
    private void doUploadImageTask(final String orignalFilePath, String uploadFile, final ImageView displayImageView) {

        if (!AndroidUtil.isNetworkAvailable(this)) { // 无网络连接
            ToastUtil.show(mContext, getString(R.string.no_connector));
            return;
        }
        
        showProgress("", "", false);
        
        MultipartRequestParams params = new MultipartRequestParams();
        params.put("fileData", new File(uploadFile));
        
        params.put("userId", mShPreferencesUtil.getUserId());

		
        String url = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.UPDATE_USER_PIC);
      
        
        OnResponseListener<JSONObject> listener = new OnResponseListener<JSONObject>(this) {
            @Override
            public void onSuccess(JSONObject response) {
                
            	Bitmap photo = BitmapFactory.decodeFile(fileImagePath);
        		img_head_icon.setImageBitmap(photo);
            }

            @Override
            public void onError(String code, String message) {
            	
                ToastUtil.show(mContext, message);
            }

            @Override
            public void onCompleted() {
                dismissProgress();
            }
        };
        executeRequest(mContext, new MultipartRequest(url, params, listener, listener));
    }
}
